package cn.edu.jxau.util;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 字符串工具类,参考commons-lang
 * StringUtil
 *
 * @author zclong 2017年8月4日
 */
public class StringUtil {
    public static final String EMPTY = "";

    /**
     * 得到一个uuid
     * @return
     */
    public static String getUUID() {
        String s = UUID.randomUUID().toString();
        return s.replace("-", "");
    }

    /**
     * 从文件路径中，重新重构这个文件名称
     * @param filePath 文件的路径，包括了文件名
     * @return 新的文件名称
     */
    public static String reConfoundFileName(String filePath) {
        File file = new File(filePath);
        return file.getParent() + UUID.randomUUID();
    }

    /**
     * 返回一个日期加密
     * @return /2017/8/23
     */
    public static String dateConfound() {
        Calendar calendar = Calendar.getInstance();
        return "/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/"
                + calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * @param css
     * @return
     */
    public static boolean arrayIsEmpty(CharSequence[] css) {
        return css == null || css.length == 0;
    }

    /**
     * <p>Checks if a CharSequence is empty ("") or null.</p>
     * <pre>
     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     * </pre>
     */
    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * <p>Checks if any one of the CharSequences are empty ("") or null.</p>
     * <pre>
     * StringUtils.isAnyEmpty(null)             = true
     * StringUtils.isAnyEmpty(null, "foo")      = true
     * StringUtils.isAnyEmpty("", "bar")        = true
     * StringUtils.isAnyEmpty("bob", "")        = true
     * StringUtils.isAnyEmpty("  bob  ", null)  = true
     * StringUtils.isAnyEmpty(" ", "bar")       = false
     * StringUtils.isAnyEmpty("foo", "bar")     = false
     * </pre>
     */
    public static boolean isAnyEmpty(final CharSequence... css) {
        if (arrayIsEmpty(css)) {
            return true;
        }
        for (final CharSequence cs : css) {
            if (isEmpty(cs)) {
                return true;
            }
        }
        return false;
    }

    /**
     * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     */
    public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (Character.isWhitespace(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

    /**
     * <p>Checks if any one of the CharSequences are blank ("") or null and not whitespace only..</p>
     * <pre>
     * StringUtils.isAnyBlank(null)             = true
     * StringUtils.isAnyBlank(null, "foo")      = true
     * StringUtils.isAnyBlank(null, null)       = true
     * StringUtils.isAnyBlank("", "bar")        = true
     * StringUtils.isAnyBlank("bob", "")        = true
     * StringUtils.isAnyBlank("  bob  ", null)  = true
     * StringUtils.isAnyBlank(" ", "bar")       = true
     * StringUtils.isAnyBlank("foo", "bar")     = false
     * </pre>
     */
    public static boolean isAnyBlank(final CharSequence... css) {
        if (arrayIsEmpty(css)) {
            return true;
        }
        for (final CharSequence cs : css) {
            if (isBlank(cs)) {
                return true;
            }
        }
        return false;
    }

    /**
     * <pre>
     * StringUtils.trim(null)          = null
     * StringUtils.trim("")            = ""
     * StringUtils.trim("     ")       = ""
     * StringUtils.trim("abc")         = "abc"
     * StringUtils.trim("    abc    ") = "abc"
     * </pre>
     */
    public static String trim(final String str) {
        return str == null ? null : str.trim();
    }

    /**
     * <pre>
     * StringUtils.trimToNull(null)          = null
     * StringUtils.trimToNull("")            = null
     * StringUtils.trimToNull("     ")       = null
     * StringUtils.trimToNull("abc")         = "abc"
     * StringUtils.trimToNull("    abc    ") = "abc"
     * </pre>
     */
    public static String trimToNull(final String str) {
        final String ts = trim(str);
        return isEmpty(ts) ? null : ts;
    }

    /**
     * <pre>
     * StringUtils.trimToEmpty(null)          = ""
     * StringUtils.trimToEmpty("")            = ""
     * StringUtils.trimToEmpty("     ")       = ""
     * StringUtils.trimToEmpty("abc")         = "abc"
     * StringUtils.trimToEmpty("    abc    ") = "abc"
     * </pre>
     */
    public static String trimToEmpty(final String str) {
        return str == null ? EMPTY : str.trim();
    }

    /**
     * @param str
     * @param prefix
     * @return
     */
    public static boolean startsWith(final String str, final String prefix) {
        if (str == null || prefix == null) {
            return str == null && prefix == null;
        }
        if (prefix.length() > str.length()) {
            return false;
        }
        return str.startsWith(prefix);
    }

    /**
     * @param string
     * @param searchStrings
     * @return
     */
    public static boolean startsWithAny(final String string, final String... searchStrings) {
        if (isEmpty(string) || arrayIsEmpty(searchStrings)) {
            return false;
        }
        for (final String searchString : searchStrings) {
            if (startsWith(string, searchString)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param str
     * @param suffix
     * @return
     */
    public static boolean endsWith(final String str, final String suffix) {
        if (str == null || suffix == null) {
            return str == null && suffix == null;
        }
        if (suffix.length() > str.length()) {
            return false;
        }
        return str.endsWith(suffix);
    }

    /**
     * @param string
     * @param searchStrings
     * @return
     */
    public static boolean endsWithAny(final String string, final String... searchStrings) {
        if (isEmpty(string) || arrayIsEmpty(searchStrings)) {
            return false;
        }
        for (final String searchString : searchStrings) {
            if (endsWith(string, searchString)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 返回是否匹配指定的字符串，如果匹配则为true,否则为false;
     *
     * @param string
     * @param regex
     * @return
     * @zclong
     * @2017年8月4日
     * @ReturnType: boolean
     */
    public static boolean matches(final String string, String regex) {
        if (isEmpty(string)) {
            return false;
        }
        return Pattern.matches(regex, string);
    }

    /**
     * 循环list中的所有元素然后删除重复的元素
     * @zclong
     * @2017年8月28日
     * @ReturnType: List
     * @param list
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static List removeDuplicate(List list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).equals(list.get(i))) {
                    list.remove(j);
                }
            }
        }
        return list;
    }
    
    /**
     * 循环list中的所有元素,根据其中值查找相同之下的元素,并根据条件查询对应的元素
     * @zclong
     * @2017年8月28日
     * @ReturnType: List
     * @param list
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static Map<Object, Object> regularDuplicate(List<HashMap<String, Object>> analysisDatas, List list, int condition) {
        int count = 0;
        HashMap<Object, Object> regular = new HashMap<Object, Object>();
        for (int i = 0; i < list.size(); i++) {
            regular.put(list.get(i), 0); // 先把List数组中的值赋给regular集合，并给每个元素赋值为0
            for (int j = 0; j < analysisDatas.size(); j++) { // 每次都出现查找
                if (list.get(i).equals(analysisDatas.get(j).get("detectedName"))) {
                    if((int) analysisDatas.get(j).get("regular") == condition) {
                        count++;
                        regular.put(list.get(i), count);
                    }
                }
            }
            count = 0;
        }
        return (Map<Object, Object>) regular;
    }
    
    /**
     * 循环list中的所有元素然后删除重复的元素并且计算重复元素的个数
     * @zclong
     * @2017年8月28日
     * @ReturnType: List
     * @param list
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static Map<Object, Object> mapDuplicate(List list) {
        int count = 0;
        HashMap<Object, Object> detected = new HashMap<Object, Object>();
        for (int i = 0; i < list.size() - 1;) {
            for (int j = list.size() - 1; j >= i; j--) {
                if (list.get(j).equals(list.get(i))) {
                    count++;
                    detected.put(list.get(i), count);
                    list.remove(j);
                }
            }
            count = 0;
        }
        return (Map<Object, Object>) detected;
    }
    
    /**
     * 循环list中的所有元素然后删除重复的元素并且计算重复元素的个数
     * @zclong
     * @2017年8月28日
     * @ReturnType: List
     * @param list
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static HashMap<String, Object> resultDatas(Map<Object, Object> detectedsMap, Map<Object, Object> regularsMap) {
        HashMap<String, Object> data = new HashMap<String, Object>();
        List<Object> object; 
        
        NumberFormat nt = NumberFormat.getPercentInstance(); //获取格式化对象,设置百分比
        nt.setMinimumFractionDigits(2);  // 精确到小数点后2位
        
        Iterator<Entry<Object, Object>> iter = detectedsMap.entrySet().iterator(); 
        while(iter.hasNext()){ 
            Entry<Object, Object> entry = iter.next(); 
            String key = (String) entry.getKey(); // 被检测物
            int count = (int) entry.getValue(); // 检测总数
            int regularCount = (int) regularsMap.get(key); // 合格数
            double proportion = regularCount/count; // 合格率
            
            object = new ArrayList(); 
            object.add(key);
            object.add(count);
            object.add(regularCount);
            object.add(nt.format(proportion));
            data.put(key, object);
        }
        return data;
    }
}
